// pages/meng/meng.js
const innerAudioContext = wx.createInnerAudioContext();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id : null,
    voiceRecordId: 0,
    title : "这是获取到的梦境标题",
    content : "这是获取到的梦境内容",
    keyword1: "无",
    keyword2: "无",
    keyword3: "无", 
    isHaipaChecked: false,
    isKaixinChecked: false,
    isShengqiChecked: false,
    isShangxinChecked: false,
    isYihanChecked: false,
    haipaInitImg: "../../images/haipa.png",
    kaixinInitImg: "../../images/kaixin.png",
    shengqiInitImg: "../../images/shengqi.png",
    shangxinInitImg: "../../images/shangxin.png",
    yihanInitImg: "../../images/yihan.png",
    worry: "这是获取到的现实困扰内容",
    history: "暂无留言记录",
    message: "", 
    btnText: "需要指点",
    btnUrl: "../information/information"
  },

  onShareAppMessage: function (res) {
    return {
      title: '解梦师',
      path: '/pages/mengjingku/mengjingku',
      success: function (res) {
        // 转发成功
        wx.showToast({
          title: '转发成功',
          icon: 'success',
          duration: 1200
        })
      },
      fail: function (res) {
        // 转发失败
        wx.showToast({
          title: '转发失败',
          icon: 'loading',
          duration: 1200
        })
      }
    }
  },

  onLoad: function (options) {
    //显示转发
    wx.showShareMenu({
      withShareTicket: true
    })
    this.setData({
      id : options.id
    })

    this.loadDreamDetail()
  },

  //分享梦境
  shareDream: function(){
    var id = this.data.id;
    wx.navigateTo({ url: '../canvas/canvas?id=' + id })
  },

  loadDreamDetail: function(){
    //获取梦境详情
    var that = this;
    var emotions = "";
    var keys = "";
    //网络请求解析
    wx.request({
      url: 'https://api.jiemengshi.com/wechat/dream/record/get',
      data: {
        recordId: that.data.id,
      },
      header: {
        'Cookie': 'JSESSIONID=' + wx.getStorageSync('sessionkey')
      },
      success: function (res) {
        console.log(res)
        console.log(res.data.data.record)
        var record = res.data.data.record
        var replies = res.data.data.replies
        var historyStr = "暂无留言记录";

        //拼装留言记录
        if (replies.length > 0) {
          historyStr = "";
          for (var i = 0; i < replies.length; i++) {
            console.log(replies[i]);
            var reply = replies[i];
            //0代表用户，非0代表管理员
            if (reply.userAdminId == 0) {
              historyStr += "我：";
              historyStr += reply.content + "\n";
            }
            else {
              historyStr += "管理员（" + reply.userAdminName + "）：";
              historyStr += reply.content + "\n";
            }
          }
        }

        emotions = record.emotion
        console.log(emotions)
        emotions = that.decodeStr(emotions)
        console.log(emotions)
        //根据表情内容设置对应图像
        for (var i = 0; i < emotions.length; i++) {
          that.setEmotion(emotions[i])
        }
        if (that.data.isHaipaChecked) {
          that.setData({
            haipaInitImg: "../../images/haipa_selected.png",
          })
        }
        if (that.data.isKaixinChecked) {
          that.setData({
            kaixinInitImg: "../../images/kaixin_selected.png",
          })
        }
        if (that.data.isShengqiChecked) {
          that.setData({
            shengqiInitImg: "../../images/shengqi_selected.png",
          })
        }
        if (that.data.isShangxinChecked) {
          that.setData({
            shangxinInitImg: "../../images/shangxin_selected.png",
          })
        }
        if (that.data.isYihanChecked) {
          that.setData({
            yihanInitImg: "../../images/yihan_selected.png",
          })
        }
        keys = record.keyWord
        keys = that.decodeStr(keys)

        //设置数据显示
        that.setData({
          title: record.title,
          content: record.content,
          voiceRecordId: record.voiceRecordId,
          history: historyStr,
          keyword1: keys[0],
          keyword2: keys[1],
          keyword3: keys[2],
          worry: record.worry
        })
      },
      fail: function () {
        wx.showToast({
          title: '请求失败',
        })
      }
    })

    // var that = this;
    // //发起网络请求：我要解梦的链接
    // wx.request({
    //   url: 'https://api.jiemengshi.com/wechat/dream/link/analyze',
    //   header: {
    //     'Cookie': 'JSESSIONID=' + wx.getStorageSync('sessionkey')
    //   },
    //   success: function (res) {
    //     console.log(res)
    //     that.setData({
    //       btnText: res.data.data.explanation,
    //       btnUrl: res.data.data.url
    //     })
    //   },
    //   fail: function () {
    //     wx.showToast({
    //       title: '请求失败',
    //     })
    //   }
    // })

  },

  //绑定留言输入事件
  listenerMessageInput:function(e){
    this.setData({
      message: e.detail.value
    })
  },

  playVoice:function(){
    //获取语音地址
    var that = this;
    //网络请求解析
    wx.request({
      url: 'https://api.jiemengshi.com/attachment/voice/url',
      data: {
        voiceRecordId: that.data.voiceRecordId,
      },
      header: {
        'Cookie': 'JSESSIONID=' + wx.getStorageSync('sessionkey')
      },
      success: function (res) {
        console.log(res.data.data)
        wx.downloadFile({
          url: res.data.data, //仅为示例，并非真实的资源
          success: function (res) {
            // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
            console.log(res)
            console.log(res.statusCode)
            console.log(res.statusCode == 200)
            if (res.statusCode == 200) {
              wx.playVoice({
                filePath: res.tempFilePath,
                success: function () {
                  wx.showToast({
                    title: '播放结束',
                    icon: 'success',
                    duration: 1000
                  })
                },
                fail: function () {
                  wx.showToast({
                    title: '播放失败',
                    icon: 'success',
                    duration: 1000
                  })
                }
              })
            }
          }
        })
          
        // innerAudioContext.src = res.data.data
        // innerAudioContext.play();
        // innerAudioContext.onPlay(() => {
        //   console.log('开始播放')
        //   wx.showToast({
        //     title: '开始播放',
        //   })
        // })
        // innerAudioContext.onEnded(() => {
        //   console.log('播放结束');
        //   wx.showToast({
        //     title: '播放结束',
        //   })
        // })
        // innerAudioContext.onError((res) => {
        //   console.log(res.errMsg)
        //   console.log(res.errCode)
        // })
      },
      fail:function(){
        wx.showToast({
          title: '请求失败',
        })
      }
    })
  },

  //留言
  leaveMessage: function (e) {
    if(this.data.message == ""){
      wx.showModal({
        title: '错误说明',
        content: "请输入留言内容",
        showCancel: false
      })
    }
    else {
      var formId = e.detail.formId;
      console.log('form发生了submit事件，推送码为：', formId)
      var that = this;
      //发起网络请求
      wx.request({
        url: 'https://api.jiemengshi.com/wechat/dream/reply/add',
        data: {
          dreamRecordId: that.data.id,
          content: that.data.message,
          formId: formId
        },
        header: {
          'Cookie': 'JSESSIONID=' + wx.getStorageSync('sessionkey')
        },
        success: function (res) {
          console.log(res)
          wx.showToast({
            title: '留言成功',
          })
          that.loadDreamDetail()
          that.setData({
            message: ""
          })
        },
        fail: function () {
          wx.showToast({
            title: '请求失败',
          })
        }
      })
    }
  },

  //修改梦境信息
  modifyInfo: function(){
    wx.navigateTo({
      url: '../modifyMeng/modifyMeng?id=' + this.data.id,
    })
  },

  //解析心情和关键词
  decodeStr:function(s){
    s = s.substring(1, s.length - 1)
    s = s.split(",")
    return s
  },

  //设置表情图片
  setEmotion:function(s){
    if(s == "害怕"){
      this.setData({
        isHaipaChecked: true
      })
    }
    if (s == "开心") {
      this.setData({
        isKaixinChecked: true
      })
    }
    if (s == "生气") {
      this.setData({
        isShengqiChecked: true
      })
    }
    if (s == "伤心") {
      this.setData({
        isShangxinChecked: true
      })
    }
    if (s == "遗憾") {
      this.setData({
        isYihanChecked: true
      })
    }
  },

  //解梦链接到解梦关键词输入页面
  jiemeng:function(){
    wx.navigateTo({
      url: this.data.btnUrl,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})